<?php
/**
 * Created by PhpStorm.
 * User: 13264
 * Date: 2019/1/17
 * Time: 21:06
 */

namespace App\Handles;


use GuzzleHttp\Client;

class UniounPayHandle
{
    const REQUEST_URL = 'http://183.129.131.55:8007';

    protected $_http_client;

    public $user_id;
    public $user_pass;
    public $acct_id;
    public $c_id;

    public function __construct()
    {
        $this->initParam();
    }

    public function initParam()
    {
        $this->_http_client = new Client();
        $this->user_id = env('UNIONPAY_USER_ID');
        $this->user_pass = env('UNIONPAY_USER_PASS');
        $this->acct_id = env('UNIONPAY_ACCT_ID');
        $this->c_id = env('UNIONPAY_C_ID');
    }

    protected function arrayToXml($data)
    {
        $xml = '';
        foreach ($data as $key=>$value){
            if(is_array($value)){
                $xml.='<'.$key.'>'.$this->arrayToXml($value).'</'.$key.'>';
                continue;
            }
            $xml .= '<'.$key.'>' . $value .  '</'.$key.'>';
        }
        return $xml;
    }

    protected function arrayToUniounpayXml($data = [])
    {
        $xml = '<FOX>';

        $xml .= $this->arrayToXml($data);

        $xml .= '</FOX>';

        return $xml;
    }

    protected function _xmlToArray($xml)
    {
        return json_decode(json_encode(simplexml_load_string($xml)),true);
    }

    public function queryWithDrawList($start_date, $end_date, $page = 1)
    {
        $data =  [
            'SIGNONMSGSRQV1' => [
                'SONRQ' => [
                    'DTCLIENT' => date('Y-m-d H:i:s'),
                    'CID' => $this->c_id,
                    'USERID' => $this->user_id,
                    'USERPASS' => $this->user_pass,
                    'GENUSERKEY' => 'N',
                ]
            ],
            'SECURITIES_MSGSRQV1' =>  [
                'SCUSTSTMTTRNRQ' =>  [
                    'TRNUID' => str_random(16),
                    'SCUSTSTMTRQ' =>  [
                        'ACCTFROM' =>  [
                            'ACCTID' => $this->acct_id,
                        ],
                        'INCTRAN' => [
                            'DTSTART' => $start_date,
                            'DTEND' => $end_date,
                            'PAGE' => $page,
                            'TRNTYPE' => '0',
                        ]
                    ]
                ]
            ]
        ];

        $xml = $this->arrayToUniounpayXml($data);

        $request_data = $this->_http_client->post(self::REQUEST_URL, ['body' => $xml]);

        return $request_data;
    }

    public function sumWithDraw($start_date, $end_date)
    {
        $list = $this->queryWithDrawList($start_date, $end_date,1);

        $arr_list = $this->_xmlToArray($list);

        return $list;
    }
}